package com.dbsecurity.filter;

import com.dbsecurity.mapper.MenuMapper;
import com.dbsecurity.pojo.Menu;
import com.dbsecurity.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @author jie
 * @date 2019/3/20 0020 -11:37
 */
@Component
public class CustomFilterInvocationSecurityMetadataSource
        implements FilterInvocationSecurityMetadataSource {

    //路径匹配器
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    MenuMapper menuMapper;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

      //提取出请求的url
      String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<Menu> allMenus = menuMapper.getAllMenus();
        //遍历menu
        for (Menu menu : allMenus) {
            //如果请求的路径与数据库中的路径相同
            if (antPathMatcher.match(menu.getPattern(),requestUrl)){
                List<Role> roles = menu.getRoles();
                String[] roleArr = new String[roles.size()];
                for (int i = 0; i < roleArr.length; i++) {
                    roleArr[i] = roles.get(i).getName();
                }
                return SecurityConfig.createList(roleArr);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    /**
     * 用来返回所有定义好的权限资源
     * @return
     */
    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        //Spring Security在启动时会校验相关配置是否正确，如果不需要检验，返回null即可
        return null;
    }

    /**
     * 返回对象是否支持检验
     * @param Clazz
     * @return
     */
    @Override
    public boolean supports(Class<?> Clazz) {
        return FilterInvocation.class.isAssignableFrom(Clazz);
    }
}
